﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Security.AccessControl;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class IM_buddylist : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string userName = IM.UserName();
            //gets the online users.
            CS_Code.IMDataContext db = new CS_Code.IMDataContext();
            var getUsersOnline = (from au in db.aspnet_Users
                                  where au.LastActivityDate >= DateTime.UtcNow.AddMinutes(-3) & au.UserName != userName
                                  select new { UserName = au.UserName });
            rptOnlineUsers.DataSource = getUsersOnline;
            rptOnlineUsers.DataBind();
            //gets the offline users
            var getUsersOffline = (from au in db.aspnet_Users
                                   where au.LastActivityDate <= DateTime.UtcNow.AddMinutes(-3) & au.UserName != userName
                                   select new { UserName = au.UserName });
            rptOfflineUsers.DataSource = getUsersOffline;
            rptOfflineUsers.DataBind();
            //CURRENT DISABLED. Gets the friends online.
            var getFriendsOnline = (from au in db.aspnet_Users
                                    from bl in db.IM_buddylists
                                    where bl.user_ID == IM.LoginID()
                                    where au.UserId == bl.buddy
                                    where au.LastActivityDate >= DateTime.UtcNow.AddMinutes(-3) & au.UserName != userName
                                    select new { UserName = au.UserName });
            rptFriends.DataSource = getFriendsOnline;
            rptFriends.DataBind();
            //check if the user has a profile or buddy ocin.
            var checkUser = (from iu in db.IM_Users
                             where iu.User_guid == IM.LoginID()
                             select new
                             {
                                 profile = iu.profile_info,
                                 icon = iu.buddy_icon_url
                             }).FirstOrDefault();
            if (checkUser != null)
            {
                tbBuddyProfile.Text = checkUser.profile;
                if (checkUser.icon != null)
                {
                    imgBuddyIcon.Visible = false;
                }
                else
                {
                    imgBuddyIcon.Visible = true;
                    imgBuddyIcon.ImageUrl = checkUser.icon;
                }
            }
            else
            { imgBuddyIcon.Visible = false; }
            //loads the buddy list.
            ddlRemoveBuddy.DataSource = removeBuddyList();
            ddlRemoveBuddy.DataBind();
            //creates the link to join a room
            aJoinRoom.HRef = "javascript:JoinGroup('" + txtbxRoomName.ClientID + "', '" + lbRoomNames.ClientID + "', '" + IM.Server_Port_Secure() + "');";
            //gets the current live groups.
            var getGroups = (from cr in db.IM_Chat_Rooms
                             select new { cr.room_name }).Distinct(); ;
            lbRoomNames.DataSource = getGroups;
            lbRoomNames.DataBind();
        }
    }

    private static IQueryable<string> removeBuddyList()
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var removeBuddyList = (from bl in db.IM_buddylists
                               from au in db.aspnet_Users
                               where bl.user_ID == IM.LoginID()
                               where au.UserId == bl.buddy
                               select au.UserName);
        return removeBuddyList;
    }
    /// <summary>
    /// binds the javascript for opening chat windows.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rptOnlineUsers_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        HtmlAnchor Item = (HtmlAnchor)e.Item.FindControl("aUserLink");
        Item.Attributes.Add("href", "javascript:commonPopup('chat.aspx?r=" + DataBinder.Eval(e.Item.DataItem, "UserName") + "',400,350,4,'Chat" + DataBinder.Eval(e.Item.DataItem, "UserName") + "');");
    }
    /// <summary>
    /// binds the javascript for opening chat windows.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rptOfflineUsers_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        HtmlAnchor Item = (HtmlAnchor)e.Item.FindControl("aUserLink");
        Item.Attributes.Add("href", "javascript:commonPopup('chat.aspx?r=" + DataBinder.Eval(e.Item.DataItem, "UserName") + "',400,350,4,'Chat" + DataBinder.Eval(e.Item.DataItem, "UserName") + "');");
    }
    /// <summary>
    /// adds a buddy to the list of buddies.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnAddBuddy_Click(object sender, EventArgs e)
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        lblWarning.Text = string.Empty;
        lblWarning.Visible = false;

        try
        {
            var checkIfBuddyExists = (from ibl in db.IM_buddylists
                                      where ibl.user_ID == IM.LoginID() && ibl.buddy == IM.LoginID(tbAddBuddyUserName.Text)
                                      select ibl.uid).FirstOrDefault();
            if (checkIfBuddyExists == 0)
            {
                CS_Code.IM_buddylist imbl = new CS_Code.IM_buddylist();
                imbl.user_ID = IM.LoginID();
                imbl.buddy = IM.LoginID(tbAddBuddyUserName.Text);
                imbl.buddy_group = tbAddBuddyGroupName.Text;
                imbl.dateTime_Updated = DateTime.UtcNow;
                db.IM_buddylists.InsertOnSubmit(imbl);
                db.SubmitChanges();
                tbAddBuddyUserName.Text = String.Empty;
                rptFriends.DataBind();
                lblWarning.Text = "User Added.";
                lblWarning.Visible = true;

                ddlRemoveBuddy.Items.Clear();
                ddlRemoveBuddy.DataSource = removeBuddyList();
                ddlRemoveBuddy.DataBind();
            }
            else
            {
                lblWarning.Text = "User is already in your buddy List.";
                lblWarning.Visible = true;
            }
        }
        catch
        {
            lblWarning.Text = "User doesn't Exist";
            lblWarning.Visible = true;
        }
    }
    /// <summary>
    /// Removes a buddy
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnRemoveBuddy_Click(object sender, EventArgs e)
    {
        lblWarning2.Text = string.Empty;
        lblWarning2.Visible = false;
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var getDelete = (from bl in db.IM_buddylists
                         where bl.user_ID == IM.LoginID() && bl.buddy == IM.LoginID(ddlRemoveBuddy.SelectedValue)
                         select bl).FirstOrDefault();
        if (getDelete != null)
        {
            db.IM_buddylists.DeleteOnSubmit(getDelete);
            db.SubmitChanges();
        }
        lblWarning2.Text = "User Removed";
        lblWarning2.Visible = true;
        ddlRemoveBuddy.Items.Clear();
        ddlRemoveBuddy.DataSource = removeBuddyList();
        ddlRemoveBuddy.DataBind();
    }
    /// <summary>
    /// saves the buddy icon and rebinds the icon.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSaveIcon_Click(object sender, EventArgs e)
    {
        if (inBuddyIcon.PostedFile.ContentLength <= 209715150)
        {
            // Declares the varaibles to be used in thus IF statement
            System.DateTime SubmitDate = DateTime.UtcNow; //declares the time and date of when the attachment was added
            string Extension = Path.GetExtension(inBuddyIcon.PostedFile.FileName).ToLower(); //This code pulls JUST the file extension of the file being uploaded
            string MIMEType = SelectCase(Extension); // Declares that MIMEType is equal to nothing
            string AttachmentTitle = Path.GetFileNameWithoutExtension(inBuddyIcon.PostedFile.FileName); //This pulls the file name only without the address of the file and without the extension.

            string VirtualPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
            VirtualPath = VirtualPath + "Data\\IM\\" + Page.User.Identity.Name;
            string FilePath = "~\\Data\\IM\\" + Page.User.Identity.Name;
            if (!(Directory.Exists(VirtualPath)))
            {
                Directory.CreateDirectory(VirtualPath);
                //directory.SetAccessControl(VirtualPath, system.Security.AccessControl.DirectorySecurity
            }

            string FileName = Path.GetFileName(inBuddyIcon.PostedFile.FileName);

            inBuddyIcon.PostedFile.SaveAs(VirtualPath + "\\" + AttachmentTitle + IM.ConvertToyyyyMMdd() + Extension);

            CS_Code.IMDataContext db = new CS_Code.IMDataContext();
            var checkUser = (from iu in db.IM_Users
                             where iu.User_guid == IM.LoginID()
                             select iu).FirstOrDefault();

            if (checkUser != null)
            {
                checkUser.buddy_icon_url = FilePath + "\\" + AttachmentTitle + IM.ConvertToyyyyMMdd() + Extension;
                checkUser.last_ping_online = DateTime.UtcNow;
                db.SubmitChanges();
            }
            else
            {
                CS_Code.IM_User imu = new CS_Code.IM_User();
                imu.User_guid = IM.LoginID();
                checkUser.buddy_icon_url = VirtualPath + "\\" + AttachmentTitle + IM.ConvertToyyyyMMdd() + Extension;
                imu.admin = 0;
                imu.is_online = 1;
                imu.last_ip = Request.UserHostAddress;
                imu.last_ping_online = DateTime.UtcNow;
                imu.nickname = Page.User.Identity.Name;
                db.IM_Users.InsertOnSubmit(imu);
                db.SubmitChanges();
            }
            imgBuddyIcon.Visible = true;
            imgBuddyIcon.ImageUrl = checkUser.buddy_icon_url;
        }
    }
    /// <summary>
    /// Selects the Case of the Type of MIME Type.
    /// </summary>
    /// <param name="Extension">Extension of File as image/ or application/</param>
    /// <returns>MIMEType</returns>
    /// <remarks></remarks>
    public static string SelectCase(string Extension)
    {
        string MIMEType = "";
        //This code decideds what mimetype the file is.
        switch (Extension)
        {
            case ".gif": //checks for .gif
                MIMEType = "image/gif"; //If it is .gif, declares the type as image/gif
                break;
            case ".jpg":
            case ".jpeg":
            case ".jpe":
                MIMEType = "image/jpeg";
                break;
            case ".png":
                MIMEType = "image/png";
                break;
            case ".tiff":
                MIMEType = "image/tiff";
                break;
            case ".pdf":
                MIMEType = "application/pdf";
                break;
            case ".zip":
                MIMEType = "application/zip";
                break;
            case ".doc":
                MIMEType = "application/doc";
                break;
            case ".xls":
                MIMEType = "application/xls";
                break;
            case ".ppt":
                MIMEType = "application/ppt";
                break;
            case ".vsd":
                MIMEType = "application/vsd";
                break;
            case ".mpp":
                MIMEType = "application/mpp";
                break;
        }
        return MIMEType;
    }
    /// <summary>
    /// save the profile infomation.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSaveProfile_Click(object sender, EventArgs e)
    {
        lblSettings.Text = string.Empty;
        lblSettings.Visible = false;
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var checkUser = (from iu in db.IM_Users
                         where iu.User_guid == IM.LoginID()
                         select iu).FirstOrDefault();
        if (checkUser != null)
        {
            checkUser.profile_info = tbBuddyProfile.Text;
            checkUser.last_ping_online = DateTime.UtcNow;
            db.SubmitChanges();
        }
        else
        {
            CS_Code.IM_User imu = new CS_Code.IM_User();
            imu.User_guid = IM.LoginID();
            imu.profile_info = tbBuddyProfile.Text;
            imu.admin = 0;
            imu.is_online = 1;
            imu.last_ip = Request.UserHostAddress;
            imu.last_ping_online = DateTime.UtcNow;
            imu.nickname = Page.User.Identity.Name;
            db.IM_Users.InsertOnSubmit(imu);
            db.SubmitChanges();
        }
        lblSettings.Text = "Profile has been updated.";
        lblSettings.Visible = true;
    }
}
